<template>
    <a-form ref="formRef" name="custom-validation" :model="formState" v-bind="layout" @finish="handleFinish">
        <a-row>
            <a-col :span="4">
                <a-form-item has-feedback label="用户账号" name="username">
                    <a-input allowClear v-model:value="formState.username" />
                </a-form-item>
            </a-col>

            <a-col :span="4">
                <a-form-item has-feedback label="操作类型" name="action_type">
                    <a-select allowClear v-model:value="formState.action_type">
                        <a-select-option value="登录">登录</a-select-option>
                        <a-select-option value="登出">登出</a-select-option>
                        <a-select-option value="新增">新增</a-select-option>
                        <a-select-option value="编辑">编辑</a-select-option>
                        <a-select-option value="删除">删除</a-select-option>
                        <a-select-option value="查询">查询</a-select-option>
                    </a-select>
                </a-form-item>
            </a-col>

            <a-col :span="8">
                <a-form-item has-feedback label="操作时间" name="action_time">
                    <a-range-picker allowClear v-model:value="formState.action_time" />
                </a-form-item>
            </a-col>

            <a-col :span="4">
                <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                    <a-button type="primary" html-type="submit">查询</a-button>
                    <!-- <a-button style="margin-left: 10px" @click="handleReset">重置</a-button> -->
                </a-form-item>
            </a-col>
        </a-row>
    </a-form>

    <a-row>
        <a-col :span="24">
            <a-table size="small" style="width: 100%;" :columns="columns" :data-source="data" :pagination="pagination"
                @change="handleTableChange">
                <template #bodyCell="{ column, text, record }">
                    <template v-if="column.dataIndex === 'action_type'">
                        <a-tag :color="getActionTypeColor(text)">{{ text }}</a-tag>
                    </template>
                    <template v-if="column.dataIndex === 'action_time'">
                        {{ formatDateTime(text) }}
                    </template>
                    <template v-if="column.dataIndex === 'action'">
                        <a @click="handleView(record)">查看详情</a>
                    </template>
                </template>
            </a-table>
        </a-col>
    </a-row>

    <a-row>
        <a-drawer v-model:open="open" class="custom-class" root-class-name="root-class-name" title="操作日志详情"
            placement="right" width="600">
            <a-descriptions :column="1" bordered>
                <a-descriptions-item label="用户账号">{{ detailData.username }}</a-descriptions-item>
                <a-descriptions-item label="操作类型">
                    <a-tag :color="getActionTypeColor(detailData.action_type)">{{ detailData.action_type }}</a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="操作模块">{{ detailData.module_name }}</a-descriptions-item>
                <a-descriptions-item label="操作描述">{{ detailData.action_desc }}</a-descriptions-item>
                <a-descriptions-item label="操作时间">{{ formatDateTime(detailData.action_time) }}</a-descriptions-item>
                <a-descriptions-item label="IP地址">{{ detailData.ip_address }}</a-descriptions-item>
                <a-descriptions-item label="用户代理">{{ detailData.user_agent }}</a-descriptions-item>
                <a-descriptions-item label="请求参数" v-if="detailData.request_params">
                    <pre>{{ JSON.stringify(JSON.parse(detailData.request_params), null, 2) }}</pre>
                </a-descriptions-item>
            </a-descriptions>
        </a-drawer>
    </a-row>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import userCtrlLogApi from '@/api/modulesApi/user_ctrl_log'
import dayjs from 'dayjs'

// 表单布局
const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
}

// 表单状态
const formState = reactive({
    username: '',
    action_type: undefined,
    action_time: [],
})

// 表格数据
const data = ref([])
const loading = ref(false)

// 分页配置
const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
})

// 表格列配置
const columns = [
    {
        title: '用户账号',
        dataIndex: 'username',
        key: 'username',
        width: 120,
    },
    {
        title: '操作类型',
        dataIndex: 'operation_type',
        key: 'operation_type',
        width: 100,
    },
    {
        title: '操作模块',
        dataIndex: 'operation_module',
        key: 'operation_module',
        width: 120,
    },
    {
        title: '操作描述',
        dataIndex: 'operation_desc',
        key: 'operation_desc',
        width: 200,
    },
    {
        title: '操作时间',
        dataIndex: 'operation_time',
        key: 'operation_time',
        width: 180,
    },
    {
        title: 'IP地址',
        dataIndex: 'ip_address',
        key: 'ip_address',
        width: 120,
    },
    // {
    //     title: '操作',
    //     dataIndex: 'action',
    //     key: 'action',
    //     width: 80,
    //     fixed: 'right',
    // },
]

// 抽屉相关
const open = ref(false)
const detailData = ref({})

// 获取操作类型颜色
const getActionTypeColor = (actionType) => {
    const colorMap = {
        '登录': 'green',
        '登出': 'orange',
        '新增': 'blue',
        '编辑': 'purple',
        '删除': 'red',
        '查询': 'cyan',
    }
    return colorMap[actionType] || 'default'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
    if (!dateTime) return ''
    return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss')
}

// 查询数据
const handleFinish = async () => {
    loading.value = true
    try {
        const params = {
            page: pagination.current,
            pageSize: pagination.pageSize,
            username: formState.username,
            action_type: formState.action_type,
            start_time: formState.action_time?.[0]?.format('YYYY-MM-DD HH:mm:ss'),
            end_time: formState.action_time?.[1]?.format('YYYY-MM-DD HH:mm:ss'),
        }

        const response = await userCtrlLogApi.getUserCtrlLog(params)
        data.value = response.data.list
        pagination.total = response.data.pagination.total
    } catch (error) {
        console.error('查询失败:', error)
        message.error('查询失败')
    } finally {
        loading.value = false
    }
}

// 重置表单
const handleReset = () => {
    formState.username = ''
    formState.action_type = undefined
    formState.action_time = []
    pagination.current = 1
    handleFinish()
}

// 表格分页变化
const handleTableChange = (pag) => {
    pagination.current = pag.current
    pagination.pageSize = pag.pageSize
    handleFinish()
}

// 查看详情
const handleView = async (record) => {
    try {
        const response = await userCtrlLogApi.getUserCtrlLogDetail({ id: record.id })
        if (response.data.code === 200) {
            detailData.value = response.data.data
            open.value = true
        } else {
            message.error(response.data.message || '获取详情失败')
        }
    } catch (error) {
        console.error('获取详情失败:', error)
        message.error('获取详情失败')
    }
}

// 组件挂载时加载数据
onMounted(() => {
    handleFinish()
})
</script>

<style scoped>
pre {
    background-color: #f5f5f5;
    padding: 8px;
    border-radius: 4px;
    font-size: 12px;
    max-height: 200px;
    overflow-y: auto;
}
</style>